//
//  CYGetdealCodeVC.m
//  CreditAddressBook
//
//  Created by Mosu&Cuu on 16/2/18.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "CYGetdealCodeVC.h"
#import "CYLoginHttpTool.h"
#import "MBProgressHUD+MJ.h"
#import "CYEscape.h"
#import "NSObject+MJKeyValue.h"
#import "CYUser.h"
#import "MobClick.h"
#import "CYJumpsTool.h"
#import "CYABTool.h"
#import "CYLoginVController.h"
#import "CYJsonInfo.h"
#import "GCD.h"
#import "CYDES3Util.h"
#import "DSNavigationBar.h"
#import "CYMeTVC.h"

#define NUMBERS @"0123456789\n"


@interface CYGetdealCodeVC ()<UIAlertViewDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *dealCodetf;
@property (weak, nonatomic) IBOutlet UITextField *ddealCodetf;
@property (weak, nonatomic) IBOutlet UITextField *phoneCode;
@property (weak, nonatomic) IBOutlet UIButton *getphoneCode;
@property (weak, nonatomic) IBOutlet UIButton *surebtn;

@property(nonatomic, strong) GCDTimer *GCDTimer;

@end

@implementation CYGetdealCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"交易密码";
    _getphoneCode.layer.cornerRadius = 5;
    _dealCodetf.secureTextEntry = YES;
    _ddealCodetf.secureTextEntry = YES;
    _surebtn.layer.cornerRadius = 5;
    _dealCodetf.delegate = self;
    _ddealCodetf.delegate = self;
    _phoneCode.delegate = self;
    
//    self.view.backgroundColor = CYColor(235, 235, 244, 1);
    self.navigationController.navigationBar.barTintColor = CYColor(99, 207, 106, 1);
    //self.view.backgroundColor = CYColor(84, 190, 248, 1);
    // Do any additional setup after loading the view from its nib.
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //主要是[receiver resignFirstResponder]在哪调用就能把receiver对应的键盘往下收
    [_dealCodetf resignFirstResponder];
    [_ddealCodetf resignFirstResponder];
    [_phoneCode resignFirstResponder];
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
     NSCharacterSet *cs;
     if(textField == _dealCodetf)
     {
          cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
          NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
          BOOL basicTest = [string isEqualToString:filtered];
          if(!basicTest)
          {
               UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                               message:@"请输入数字"
                                                              delegate:nil
                                                     cancelButtonTitle:@"确定"
                                                     otherButtonTitles:nil];
               
               [alert show];
               return NO;
          }
     }
     
     //其他的类型不需要检测，直接写入
     return YES;        
}

- (IBAction)getphone:(id)sender {
   [self countdown:sender];
    CYUser *user = [CYLoginHttpTool userData].user;
    //确认网络有连接后发送短信验证码
    [CYLoginHttpTool sendSMSWithPhone:user.phone success:^(id json) {
        //CYLog(@"sms: %@", json);
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            [MBProgressHUD showSuccess:jsonInfo.message];
            
        }else {
            [MBProgressHUD showError:jsonInfo.message];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showError:CYServerConnectFailure];

    }];
}
/**
 *  倒计时
 */

- (void)countdown:(UIButton *)btn {
    self.GCDTimer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
    
    CYWeakObject(weakself, self);
    __block int time = 119;
    [self.GCDTimer event:^{
        if (time < 1) {
            //设置界面的按钮显示 根据自己需求设置
            [btn setTitle:@"发送验证码" forState:UIControlStateNormal];
            btn.userInteractionEnabled = YES;
//            btn.backgroundColor = CYColor(79, 118, 245, 1);
            [weakself.GCDTimer destroy];
        } else {
            //        NSLog(@"time:%d", time);
            [btn setTitle:[NSString stringWithFormat:@"%dS",time] forState:UIControlStateNormal];
            btn.userInteractionEnabled = NO;
//            btn.backgroundColor = CYColor(211, 211, 211, 1);
        }
        time--;
    } timeInterval:NSEC_PER_SEC * 1];
    [self.GCDTimer start];
}

- (IBAction)suresend:(id)sender {
    
    CYUser *user = [CYLoginHttpTool userData].user;
    if ([self.dealCodetf.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请输入交易密码"];
    }else if ([self.phoneCode.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请输入验证码"];
    }else if ([self.ddealCodetf.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请确认交易密码"];
    }else {
        
        if ([self.dealCodetf.text isEqualToString:@""] || (self.dealCodetf.text.length != 6)) {
            CYAlertView(@"请输入正确的6位密码！");
            return;
        }else{
            if ([self.dealCodetf.text isEqualToString:self.ddealCodetf.text]) {
                NSString *desstr = [CYDES3Util encrypt:self.dealCodetf.text];
                NSString *ddesstr = [CYDES3Util encrypt:self.ddealCodetf.text];
                [CYHttpTool postWithURL:[CYURL shared].bandDealCode params:@{@"userId":user.userId,@"token":user.token,@"newDealCode":desstr,@"dnewDealCode":ddesstr,@"phoneCode":self.phoneCode.text} success:^(id json) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"CYDealCodeNotification" object:nil userInfo:nil];
                    [MBProgressHUD hideHUDForView:self.view];
                    CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
                    NSString *data = jsonInfo.message;
                    UIAlertView *aletview = [[UIAlertView alloc]initWithTitle:@"提示" message:data delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
                    [aletview show];
                     if (jsonInfo.isSuccess) {
                          [CYJumpsTool jumpToMain:self.view];
                     }
                } failure:^(NSError *error) {
                    
                }];
            }else{
                 CYAlertView(@"两次密码输入不一致");
            }
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {

    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [DSNavigationBar setNavigationBarWithNavigationBar:self.navigationController.navigationBar color:CYColor(99, 207, 106, 1)];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
